package com.wbdgj.ui.mine;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import com.igexin.sdk.PushManager;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;
import com.wbdgj.R;
import com.wbdgj.base.BaseActivity;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.base.BaseUiListener;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.OnNoResponseListener;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.ui.MainActivity;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.utils.ContextUtils;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;
import com.wbdgj.utils.dialog.ConfirmDialog;
import com.wbdgj.views.AllRoundImageView;
import com.wbdgj.views.ArcImageView;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import jp.wasabeef.glide.transformations.BlurTransformation;
import retrofit2.Call;

/**
 * Created by Administrator on 2018/6/1.
 */

public class InformaticaNewActivity extends BaseActivity{

    @BindView(R.id.name)
    TextView name;

    @BindView(R.id.sex)
    TextView sex;

    @BindView(R.id.card)
    TextView card;

    @BindView(R.id.cardTxt)
    TextView cardTxt;

    @BindView(R.id.roundImg)
    AllRoundImageView roundImg;

    @BindView(R.id.ljImg)
    ArcImageView ljImg;

    @BindView(R.id.idcard)
    TextView idcard;

    @BindView(R.id.phone)
    TextView phone;

    @BindView(R.id.NICKNAME)
    TextView nickname;

    @BindView(R.id.levlel)
    TextView levlel;

    @BindView(R.id.levelLay)
    LinearLayout levelLay;
    @BindView(R.id.levelImg)
    ImageView levelImg;
    @BindView(R.id.smImg)
    ImageView smImg;

    private static TextView wx;
    @BindView(R.id.qq)
    TextView qq;

    private Context context = this;
    private final int SDK_PERMISSION_REQUEST = 127;

    private static boolean wxBd = false;
    private boolean qqBd = false;

    private Tencent mTencent;
    private String QQAppID = "101529516";
    private String Scope = "get_user_info,add_t,qrcode";
    private BaseUiListener listener;
    private IWXAPI mIwxapi;
    private String wechatAppID = "wxf1069c4f961f956e";

    @Override
    protected int getLayoutResId() {
        return R.layout.ui_information_new;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void initView() {
        wx = (TextView) findViewById(R.id.wx);
        // 获取IWXAPI 实例
        mIwxapi = WXAPIFactory.createWXAPI(context, wechatAppID, false);
        // 将应用的APPID 注册到微信
        mIwxapi.registerApp(wechatAppID);
        mTencent = Tencent.createInstance(QQAppID, context);
        listener = new BaseUiListener() {
            @Override
            protected void doComplete(JSONObject values) {
                super.doComplete(values);
                Gson gson = new Gson();
                JsonObject jsonObject  = gson.fromJson(values+"", JsonObject.class);
                Log.e("zp",  String.valueOf(jsonObject.get("openid")).replace("\"", ""));
                bindqq( String.valueOf(jsonObject.get("openid")).replace("\"", ""));
            }
        };
        getMbUserInfo();
        findViewById(R.id.nicknameLay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(context, ChangeNickNameActivity.class), 1);
            }
        });
        findViewById(R.id.NICKNAME).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(context, ChangeNickNameActivity.class), 1);
            }
        });
        findViewById(R.id.btn_top_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launch(MyEwmActivity.class);
            }
        });
        findViewById(R.id.roundImg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPersimmions();
            }
        });
        findViewById(R.id.phoneLay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//               startActivity(new Intent(context, IdentityVeriActivity.class));
               startActivity(new Intent(context, IdentityVeriChangeActivity.class));
            }
        });
        findViewById(R.id.wxLay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (wxBd){
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, "确定微信解绑吗？", 1);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                            wunbind();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }else{
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.WXFROM, "2");
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "wechat_sdk_test";
                    mIwxapi.sendReq(req);
                }

            }
        });
        findViewById(R.id.qqLay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (qqBd){
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context, "确定QQ解绑吗？", 1);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                            qunbind();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }else{
                    mTencent.login(InformaticaNewActivity.this, Scope, listener);
                }

            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1){
            getMbUserInfo();
        }
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, listener);
            Log.e("zp", "resultCode="+resultCode);
        }
        if (resultCode == 5) {

            Log.e("zp", "resultCode11111=");
        }

    }

    public static void find(){
        wx.setText("已绑定");
        wxBd = true;
    }

    private void wunbind() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().wunbind(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(this) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                    getMbUserInfo();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void qunbind() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().qunbind(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(this) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                    getMbUserInfo();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void getMbUserInfo() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().getMbUserInfo(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    if ((linkedTreeMap.get("NAME")+"").equals("null")){
                    }else{
                        name.setText(linkedTreeMap.get("NAME")+"");
                    }

                    if ((linkedTreeMap.get("PT_CARD")+"").equals("null")){
                        card.setText("");
                    }else{
                        card.setText(""+linkedTreeMap.get("PT_CARD"));
                    }
                    if (linkedTreeMap.containsKey("SEX")){
                        if (decimalFormat.format(linkedTreeMap.get("SEX")).equals("1")){
                            sex.setText("男");
                            smImg.setBackgroundResource(R.mipmap.bsm);
                        }else{
                            sex.setText("女");
                            smImg.setBackgroundResource(R.mipmap.gsm);
                        }
                    }


                    if (linkedTreeMap.containsKey("NICKNAME")){
                        nickname.setText(linkedTreeMap.get("NICKNAME")+"");
                    }else{
                        nickname.setText("请设置");
                    }
                    idcard.setText(ContextUtils.settingID(linkedTreeMap.get("ID_CARD")+""));
                    card.setText(linkedTreeMap.get("PT_CARD")+"");
                    phone.setText(linkedTreeMap.get("PHONE")+"");
                    if (linkedTreeMap.containsKey("LEVEL")){
                        if (decimalFormat.format(linkedTreeMap.get("LEVEL")).equals("1")){
                            levelLay.setBackgroundResource(R.mipmap.v_01_bg);
                            levelImg.setBackgroundResource(R.mipmap.v_01);
                            cardTxt.setText("普通会员");
                            cardTxt.setTextColor(getResources().getColor(R.color.v_01));
                        }else if (decimalFormat.format(linkedTreeMap.get("LEVEL")).equals("2")){
                            levelLay.setBackgroundResource(R.mipmap.v_02_bg);
                            levelImg.setBackgroundResource(R.mipmap.v_02);
                            cardTxt.setText("黄金会员");
                            cardTxt.setTextColor(getResources().getColor(R.color.v_02));
                        }else if (decimalFormat.format(linkedTreeMap.get("LEVEL")).equals("3")){
                            cardTxt.setText("白金会员");
                            cardTxt.setTextColor(getResources().getColor(R.color.v_03));
                            levelLay.setBackgroundResource(R.mipmap.v_03_bg);
                            levelImg.setBackgroundResource(R.mipmap.v_03);
                        }else if (decimalFormat.format(linkedTreeMap.get("LEVEL")).equals("4")){
                            cardTxt.setText("钻石会员");
                            cardTxt.setTextColor(getResources().getColor(R.color.v_04));
                            levelLay.setBackgroundResource(R.mipmap.v_04_bg);
                            levelImg.setBackgroundResource(R.mipmap.v_04);
                        }else if (decimalFormat.format(linkedTreeMap.get("LEVEL")).equals("5")){
                            cardTxt.setText("黑钻会员");
                            cardTxt.setTextColor(getResources().getColor(R.color.v_05));
                            levelLay.setBackgroundResource(R.mipmap.v_05_bg);
                            levelImg.setBackgroundResource(R.mipmap.v_05);
                        }else if (decimalFormat.format(linkedTreeMap.get("LEVEL")).equals("6")){
                            cardTxt.setText("股东会员");
                            cardTxt.setTextColor(getResources().getColor(R.color.v_06));
                            levelLay.setBackgroundResource(R.mipmap.v_06_bg);
                            levelImg.setBackgroundResource(R.mipmap.v_06);
                        }else{
                            cardTxt.setText("普通会员");
                            cardTxt.setTextColor(getResources().getColor(R.color.v_01));
                            levelLay.setBackgroundResource(R.mipmap.v_01_bg);
                            levelImg.setBackgroundResource(R.mipmap.v_01);
                        }
                    }

                    if (!(linkedTreeMap.get("IMG")+"").equals("null")){
                        Glide.with(context).load(HttpAdapter.HEAD_URL+linkedTreeMap.get("IMG")).placeholder(R.mipmap.mine_photo).error(R.mipmap.mine_photo).into(roundImg);
                    }else{
                        Glide.with(context).load("").placeholder(R.mipmap.mine_photo).error(R.mipmap.mine_photo).into(roundImg);
                    }
                    Glide
                            .with(context)
                            .load(HttpAdapter.HEAD_URL+linkedTreeMap.get("IMG"))
                            .error(R.mipmap.mine_new_bg)
                            .centerCrop()
                            .crossFade()
                            .dontAnimate()
                            .bitmapTransform(new BlurTransformation(context,23,4))
                            .into(ljImg);

                    if (linkedTreeMap.containsKey("weixin")){
                        if (decimalFormat.format(linkedTreeMap.get("weixin")).equals("1")){
                            wx.setText("已绑定");
                            wxBd = true;
                        }else{
                            wx.setText("未绑定");
                            wxBd = false;
                        }
                    }else{
                        wxBd = false;
                        wx.setText("未绑定");
                    }
                    if (linkedTreeMap.containsKey("qq")){
                        if (decimalFormat.format(linkedTreeMap.get("qq")).equals("1")){
                            qq.setText("已绑定");
                            qqBd = true;
                        }else{
                            qq.setText("未绑定");
                            qqBd = false;
                        }
                    }else{
                        qq.setText("未绑定");
                        qqBd = false;
                    }
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (addPermission(permissions, Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                Log.e("zp", "111");
//                startActivityForResult(new Intent(context, PhotoUploadActivity.class),1);
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            Log.e("zp", "222");
            startActivityForResult(new Intent(context, PhotoUploadActivity.class),1);
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void bindqq(final String opid) {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().bindqq(opid, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnNoResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort("绑定成功");
                    getMbUserInfo();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }
}
